<?php echo form_tag('mr2/save', array(
  'id'        => 'sf_admin_edit_form',
  'name'      => 'sf_admin_edit_form',
  'multipart' => true,
)) ?>

<?php echo object_input_hidden_tag($mr2, 'getId') ?>

<fieldset id="sf_fieldset_none" class="">
<?php
    if ($mr2->getReviseId()) { ?>
        <input type="hidden" name="mr2[revise_id]" id="mr2[revise_id]" value="<?php echo $mr2->getReviseId() ?>" >
<?}
?>
<div class="form-row">
  <?php echo label_for('mr2[mrno]', __($labels['mr2{mrno}']), 'class="required" ') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{mrno}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{mrno}')): ?>
    <?php echo form_error('mr2{mrno}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <!--Tien code here-->
  <?php $default = CommonValues::GenerateAutoNumber('MR2', $mr2->getMrno(), 'MRSub')   ?>
   
   <input name="mr2_mrno_show" id="mr2_mrno_show" value="<?php echo $default ?>" size="15" disabled="disabled" type="text">
   </div>
</div>

<div class="form-row">
  <?php echo label_for('mr2[category]', __($labels['mr2{category}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{category}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{category}')): ?>
    <?php echo form_error('mr2{category}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php
    $categoryDefault = 2;
    if ($mr2->getCategory() != null ) $categoryDefault = $mr2->getCategory(); 
  ?>
  <select name="mr2[category]" id="mr2_category">
    <?php foreach (CommonValues::$gMRCategory['display'] as $key=>$category) { 
    if ($mr2->user->hasCredential(CommonValues::$gMRCategory['permission'][$key])){ ?>
    <option value="<?php echo $category;  if ($category == $categoryDefault) echo '" selected="1'?>"><?php echo $key ?></option>
    <?php } }?>
    </select>
    </div>
</div>
<div id ="project">
<? if ($categoryDefault == CommonValues::$gMRCategory['key']['Project']) {?>
<div class="form-row">
  <?php echo label_for('mr2[project_id]', __($labels['mr2{project_id}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{project_id}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{project_id}')): ?>
    <?php echo form_error('mr2{project_id}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_select_tag($mr2, 'getProjectId', array (
  'related_class' => 'Project',
  'control_name' => 'mr2[project_id]',
  'include_blank' => true,
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>
<?} else {?>
<input type="hidden" name = "mr2[project_id]" id="mr2_project_id" value ="0">
<?}?>
</div>

<div class="form-row">
  <?php echo label_for('mr2[created_at]', __($labels['mr2{created_at}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{created_at}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{created_at}')): ?>
    <?php echo form_error('mr2{created_at}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_input_date_tag($mr2, 'getCreatedAt', array (
  'rich' => true,
  'calendar_button_img' => '/sf/sf_admin/images/date.png',
  'control_name' => 'mr2[created_at]',
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>

<div class="form-row">
  <?php echo label_for('mr2[reqarrdate]', __($labels['mr2{reqarrdate}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{reqarrdate}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{reqarrdate}')): ?>
    <?php echo form_error('mr2{reqarrdate}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php $value = object_input_date_tag($mr2, 'getReqarrdate', array (
  'rich' => true,
  'calendar_button_img' => '/sf/sf_admin/images/date.png',
  'control_name' => 'mr2[reqarrdate]',
)); echo $value ? $value : '&nbsp;' ?>
    </div>
</div>



<div class="form-row">
  <?php echo label_for('mr2[status]', __($labels['mr2{status}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{status}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{status}')): ?>
    <?php echo form_error('mr2{status}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php  $status = $mr2->getStatus()?  $mr2->getStatus(): 0?> 
  <input type="text" name ="mr_show" id ="mr_show" disabled="1"  value="<?php echo CommonValues::$gMRStatus['value'][$status]?>">
  <input type="hidden" name ="mr2[status]" id ="mr2_status" value="<?php echo $status?>">
    </div>
</div>

<div class="form-row">
  <?php echo label_for('mr2[approvalstatus]', __($labels['mr2{approvalstatus}']), '') ?>
  <div class="content<?php if ($sf_request->hasError('mr2{approvalstatus}')): ?> form-error<?php endif; ?>">
  <?php if ($sf_request->hasError('mr2{approvalstatus}')): ?>
    <?php echo form_error('mr2{approvalstatus}', array('class' => 'form-error-msg')) ?>
  <?php endif; ?>

  <?php  $status = $mr2->getApprovalstatus()?  $mr2->getApprovalstatus(): 0?> 
  <input type="text" name ="mr_show" id ="mr_show" disabled="1"  value="<?php echo CommonValues::$gMRApprovalStatus['value'][$status]?>">
  <input type="hidden" name ="mr2[approvalstatus]" id ="mr2_approvalstatus" value="<?php echo $status?>">
    </div>
</div>


</fieldset>

<!--Tien code here
get information for MR-->
<?php
    if ($mr2->getComponentgroupId()){
        $componentGroupId = $mr2->getComponentgroupId();
        
        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
        $c->addAscendingOrderByColumn(ComponentsPeer::ID);
        
        $componentList = ComponentsPeer::doSelect($c);
    }
?>


<?php 
echo link_to_remote('', array('update' => 'list_component', 
  'url' => 'component/listAjax', 
  'loading' => visual_effect('appear', 'indicator'),
  'complete' => visual_effect('fade', 'indicator'). visual_effect('highlight', 'list_component'),
  'position' => 'bottom',
));
?>

<div id="sf_admin_bar">

<div class="sf_admin_filters">

  <fieldset>
    <h2>Filters</h2>

    <div class="form-row">
    <label for="filters_alert_date">Description:</label>
    <div class="content">
        <input type="text" name="description" id="description" />
        <input type="hidden" name="category" id="category"  value="1" />
    </div>
    </div>
    
    <div class="form-row">
    <label for="filters_alert_date">Product Code:</label>
    <div class="content">
        <input type="text" name="productcode" id="productcode" />
    </div>
    </div>

   </fieldset>

	  <ul class="sf_admin_actions">    
	    <li><input type="button" name="filter" value="Filter" class="sf_admin_action_filter"  onclick="changeList()" /></li>
	  </ul>
	  
    <div id="indicator" style="display: none">Loading...</div>

    
</div>
</div>  	    
       <div id ="list_component">    
          <table id ='ListOfComponents' "cellspacing="0" class="sf_admin_list">            
            <thead>
            <tr>
                  <th id="sf_admin_list_th_productcode" width="25%">Product Code
                          </th>
                  <th id="sf_admin_list_th_description" width="35%">Description
                          </th>
                  <th id="sf_admin_list_th_description" width="20%">Brand
                          </th>       
                  <th id="sf_admin_list_th_description" width="15%">Unit
                          </th>
                  <th id="sf_admin_list_th_description" width="5%">Add
                          </th>
            </tr>
            </thead>            
          </table>
       </div>
            
           
    
    <ul class="sf_admin_actions">    
	    <li><input type="button" name="Add Components" value="Add Components" class="sf_admin_action_filter"  onclick="addComponents()" /></li>	    
    </ul>

<table id ='added_components' "cellspacing="0" class="sf_admin_list">
<thead>
<tr>
      <th id="sf_admin_list_th_productcode" width="25%">Product Code
              </th>
      <th id="sf_admin_list_th_description" width="35%">Description
              </th>
      <th id="sf_admin_list_th_description" width="10%">Brand
              </th>       
      <th id="sf_admin_list_th_description" width="5%">Unit
              </th>
      <th id="sf_admin_list_th_description" width="5%">Exp Dlv Date (dd-mm-yy)</th>
      
      <th id="sf_admin_list_th_description">Qty to request</th>
      <th id="sf_admin_list_th_description">Min stock (%)</th>
      
      <th id="sf_admin_list_th_description" width="5%">Action
              </th>
</tr>
</thead>
<!--show component here-->
<?php if (isset($mr2->rowIds) && count($mr2->rowIds)) {
    foreach ($mr2->rowIds as $key=>$id) { 
        $component1= ComponentPeer::retrieveByPK($id);
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID , $component1->getId());
        $warehouse = WarehousePeer::doSelectOne($c);?>
        <tr class="sf_admin_row_<?php echo $key%2?>">
            <input type="hidden" name="rowIds[]" id ="rowIds"  class = "ExistComponents" value="<? echo $component1->getId()?>"/>
            <td><?echo $component1->getProductcode()?></td>
            <td><?echo $component1->getDescription()?></td>
            <td><?echo $component1->getBrand()?></td>
            <td><?echo $component1->getComponentunit()?></td>
            <td><input type="text" name="expdates[]" id ="expdates" size="8" value ="<?echo $mr2->expdates[$key]?>"></td>
            <td><input type="text" name="qtys[]" id ="qtys" size="5" class="QTYS" onkeyup="calcMinStock()" value ="<?echo $mr2->qtys[$key]?>">
            <input type="hidden" name="minStockQtys[]" id ="minStockQtys"  class = "MINSTOCKQTYS" value="<?php echo $component1->getMinstockqty()?>"/>
            <input type="hidden" name="stockQtys[]" id ="stockQtys"  class = "STOCKQTYS" value="<?php  echo $warehouse->getClosing()?>"/>
            </td>
            <td><input type="text" name="minStocks[]" id ="minStocks" class ="MINSTOCKS" size="2" readonly ="1" value ="<?echo $mr2->minStocks[$key]?>"></td>
            <td><ul class="sf_admin_td_actions"><li><?php echo  image_tag(sfConfig::get('sf_admin_web_dir').'/images/delete_icon.png', array('align' => 'absmiddle', 'alt' => 'delete', 'title' =>'delete', 'onclick' => 'removeComponent('.$component1->getId().',"added_components", ".ExistComponents")', 'onmouseover'=>'this.style.cursor="pointer"'))?></li></ul></td>
        </tr>
<?} } elseif (isset($componentList) && $componentList) {
    foreach ($componentList as $key=>$components) { 
        $component1= ComponentPeer::retrieveByPK($components->getComponentId());
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID , $component1->getId());
        $warehouse = WarehousePeer::doSelectOne($c);
        ?>
        <tr class="sf_admin_row_<?php echo $key%2?>">
            <input type="hidden" name="rowIds[]" id ="rowIds"  class = "ExistComponents" value="<? echo $component1->getId()?>"/>
            <td><?echo $component1->getProductcode()?></td>
            <td><?echo $component1->getDescription()?></td>
            <td><?echo $component1->getBrand()?></td>
            <td><?echo $component1->getComponentunit()?></td>            
            <td><input type="text" name="expdates[]" id ="expdates" size="8" value ="<?echo $components->getDate("d-m-Y")?>"></td>
            <td><input type="text" name="qtys[]" id ="qtys" size="5" class="QTYS" onkeyup="calcMinStock()" value ="<?echo $components->getQty1()?>">
            <input type="hidden" name="minStockQtys[]" id ="minStockQtys"  class = "MINSTOCKQTYS" value="<?php echo $component1->getMinstockqty()?>"/>
            <input type="hidden" name="stockQtys[]" id ="stockQtys"  class = "STOCKQTYS" value="<?php  echo $warehouse->getClosing()?>"/>
            </td>
            <td><input type="text" name="minStocks[]" id ="minStocks" class ="MINSTOCKS" size="3" readonly ="1" value ="<?echo $components->getQty2()?>"></td>
            <td><ul class="sf_admin_td_actions"><li><?php echo  image_tag(sfConfig::get('sf_admin_web_dir').'/images/delete_icon.png', array('align' => 'absmiddle', 'alt' => 'delete', 'title' =>'delete', 'onclick' => 'removeComponent('.$component1->getId().',"added_components", ".ExistComponents")', 'onmouseover'=>'this.style.cursor="pointer"'))?></li></ul></td>
        </tr>
<?php } }?>
</table>

<script type="text/javascript">

function changeList() {
    var description=$("description").value;
    var productcode=$("productcode").value;
    var category = $("category").value;
    var link = '<?php echo url_for('component/listAjax') ?>';
    new Ajax.Updater('list_component', link + '?description='+ description + '&productcode=' + productcode + '&category=' + category, {asynchronous:true, evalScripts:false, onComplete:function(request, json){new Effect.Fade('indicator', {});new Effect.Highlight('list_component', {});}, onLoading:function(request, json){new Effect.Appear('indicator', {});}});  
}

function addComponents()
{
    var components = $$(".ChkboxComponents");        
    var existComponents = $$(".ExistComponents");                
    var table = $("added_components");
    var count = table.rows.length;
    
    for (var i =0; i< components.length ; i++ ){
        if (components[i].checked){
            var component = components[i];            
            var rowId = component.attributes['rowId'].value;
            var bExist = false;
            for (var j =0; j< existComponents.length; j++)
                if (rowId== existComponents[j].value){
                    bExist = true;
                    break;
                }
            if (!bExist) {            
                var oddRow=(count+1) % 2;
                var productCode='<td>' + $("productCode_"+ rowId).value + '</td>';          
                var description='<td>'+ $("description_"+ rowId).value + '</td>';          
                var brand='<td>' + $("brand_"+ rowId ).value + '</td>';  
                var unit='<td>' + $("unit_"+ rowId ).value + '</td>';
                var rowIds = '<input type="hidden" name="rowIds[]" id ="rowIds"  class = "ExistComponents" value="' + rowId+ '"/>' ;                         
                var action = '<td><ul class="sf_admin_td_actions"><li>' + '<?php echo  image_tag(sfConfig::get('sf_admin_web_dir').'/images/delete_icon.png', array('align' => 'absmiddle', 'alt' => 'delete', 'title' =>'delete', 'onclick' => 'removeComponent(ROWID, "added_components", ".ExistComponents")', 'onmouseover'=>'this.style.cursor="pointer"') ); ?>' +  '</li></ul></td>';
                action = action.replace("ROWID", rowId);
                
                var qty='<td><input type="text" name="qtys[]" id="qtys" size="5" class ="QTYS" onkeyup="calcMinStock()" /><input type="hidden" name="minStockQtys[]" id ="minStockQtys"  class = "MINSTOCKQTYS" value="' + $("minStockQty_" + rowId).value + '"/><input type="hidden" name="stockQtys[]" id ="stockQtys"  class = "STOCKQTYS" value="' + $("stockQty_" + rowId).value + '"/></td>';
                var minStock='<td><input type="text" name="minStocks[]" id="minStocks" size="2" class="MINSTOCKS" readonly="1" /></td>';
                var expdate ='<td><input name="expdates[]" id="expdates" value="" size="8" type="text"></td>';
                var newRow = table.insertRow(count);
                newRow.className = 'sf_admin_row_'+ oddRow;
                newRow.innerHTML= rowIds +  productCode + description+ brand + unit + expdate +  qty  + minStock + action;
                ++count;
            }                       
        }
        
    }
    //remove component  row after add to exist
    var componentList = $("ListOfComponents");
    var j=0;
    for (var i =0; i< components.length ;  i++){
        if (components[i].checked){
            var component = components[i];            
            var rowId = component.attributes['rowId'].value;
             componentList.deleteRow(i+1 - j);
             j++;
        }
    }
    //change classname, begin from 1 because there is a row with thead title
    for (var i =1; i< componentList.rows.length; i++)    {
        componentList.rows[i].className='sf_admin_row_' + (i+1)%2;
    }
}

function removeComponent(rowId, tableId, classId){
    var existComponents = $$(classId);
    var components = $(tableId);
    
    for (var i =0; i < existComponents.length; i++){
        if (rowId == existComponents[i].value){
            components.deleteRow(i+1);
            break;
        }        
    }
    //because there is a row with thead title
    for (var i =1; i< components.rows.length; i++)    {
        components.rows[i].className='sf_admin_row_'+ (i+1)%2;
    }
}

function calcMinStock() {

    var qtys = $$(".QTYS");
    var minStocks= $$(".MINSTOCKS");
    var minStockQtys= $$(".MINSTOCKQTYS");
    //var stockQtys= $$(".STOCKQTYS");
    
    for (var i =0; i < qtys.length; i++){
        if (qtys[i].value >0 && minStockQtys[i].value > 0) {            
            minStocks[i].value = ((qtys[i].value*1.0 ) / (minStockQtys[i].value*1.0))* 100.0;
        }
        else minStocks[i].value= '';
    }
}

function changeProject() {
    var category = $("mr2_category");
    var value = category.options[category.selectedIndex].value;
    
    var project = $("project");
    project.innerHTML ='';
    
    if (category.selectedIndex >= 0) {        
        var link = '<?php echo url_for('mr2/GenerateProject') ?>';
        new Ajax.Updater('project', link + '?category='+ value );
    }
}
</script>


<?php include_partial('edit_actions', array('mr2' => $mr2)) ?>

</form>

<ul class="sf_admin_actions">
      <li class="float-left"><?php if ($mr2->getId()): ?>
<?php echo button_to(__('delete'), 'mr2/delete?id='.$mr2->getId(), array (
  'post' => true,
  'confirm' => __('Are you sure?'),
  'class' => 'sf_admin_action_delete',
)) ?><?php endif; ?>
</li>
  </ul>
